<template>
  <div class="receipt-order-edit-wrapper app-container">
    <div class="receipt-order-content">
      <el-row>
        <el-col :span="24">
          <div class="flex-container justify-end">
            <el-button @click="submitForm" type="primary">保存</el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
          <el-divider></el-divider>
        </el-col>
      </el-row>
      <el-form :model="form" ref="form" inline :rules="rules">
        <el-form-item label="入库单号" prop="receiptOrderNo">
          <el-input
            class="w200"
            v-model="form.receiptOrderNo"
            placeholder="入库单号"
            disabled="disabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <WmsSupplierSelect v-model="form.supplierId"></WmsSupplierSelect>
        </el-form-item>
        <el-form-item label="经手人" prop="handlerId">
          <WmsUser v-model="form.handlerId"></WmsUser>
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <WmsUserDepartment v-model="form.departmentId"></WmsUserDepartment>
        </el-form-item>
        <el-form-item label="票据类型" prop="receiptType">
          <el-select v-model="form.receiptType" placeholder="请选择">
            <el-option
              v-for="item in dict.type.wms_bill_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              {{ item.label }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款类型" prop="paymentType">
          <el-select v-model="form.paymentType" placeholder="请选择">
            <el-option
              v-for="item in dict.type.wms_payment_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              {{ item.label }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货币" prop="currency">
          <el-select v-model="form.currency" placeholder="请选择">
            <el-option
              v-for="item in dict.type.wms_currency"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              {{ item.label }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="汇率" prop="exchangeRate">
          <el-input
            class="w100"
            v-model="form.exchangeRate"
            placeholder="汇率"
          ></el-input>
        </el-form-item>

        <el-form-item label="已付定金" prop="payableAmount">
          <el-input
            class="w200"
            v-model="form.payableAmount"
            placeholder="请输入已付定金"
            disabled="disabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="备注...100个字符以内"
            rows="1"
            maxlength="100"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <div class="flex-center mb8">
        <div class="flex-one large-tip bolder-font">
          <el-row class="mb8 mt10" :gutter="10">
            <el-col :span="1.5">
              <div class="flex-one large-tip bolder-font">物料明细</div>
            </el-col>
          </el-row>
        </div>
        <div class="ops">
          <el-button
            type="primary"
            plain="plain"
            size="small"
            @click="showAddItem"
            >添加物料</el-button
          >
        </div>
      </div>
      <div class="table">
        <WmsTable
          :data="form.materialDetails"
          @selection-change="handleSelectionChange"
        >
         <el-table-column
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column label="分类" align="center" prop="categoryName" width="100"></el-table-column>
          <el-table-column label="型号" align="center" prop="modelName" width="100"></el-table-column>
          <el-table-column label="厚度" align="center" prop="thicknessName" width="100"></el-table-column>
          <el-table-column label="宽幅" align="center" prop="widthName" width="100"></el-table-column>
          <el-table-column label="规格" align="center" prop="specificationName" width="100"></el-table-column>
          <el-table-column label="仓库" align="center" prop="warehouseName" width="100"></el-table-column>
          <el-table-column label="仓位" align="center" prop="warehousePositionName" width="100"></el-table-column>
          <el-table-column label="需求时间" align="center" prop="demandDate" width="100"></el-table-column>
          <el-table-column label="预计到货" align="center" prop="expectedArrivalDate" width="100"></el-table-column>
          <el-table-column label="在途信息" align="center" prop="inTransitInformation" width="100"></el-table-column>
          <el-table-column label="性质" align="center" prop="natureName" width="100"></el-table-column>
          <el-table-column label="备注" align="center" prop="remarks" width="100"></el-table-column>
          <el-table-column label="件数" align="center" prop="pieceCount" width="100"></el-table-column>
          <el-table-column label="件数单位" align="center" prop="pieceUnit" width="100"></el-table-column>
          <el-table-column label="数量" align="center" prop="quantity" width="100"></el-table-column>
          <el-table-column label="单位" align="center" prop="unitName" width="100"></el-table-column>
          <el-table-column label="单价" align="center" prop="unitPrice" width="100"></el-table-column>
          <el-table-column label="计价数量" align="center" prop="valuationQuantity" width="100"></el-table-column>
          <el-table-column label="计价单位" align="center" prop="valuationUnit" width="100"></el-table-column>
          <el-table-column label="金额" align="center" prop="amount" width="100"></el-table-column>
          <el-table-column label="税率%" align="center" prop="taxInclusivePrice" width="100"></el-table-column>
          <el-table-column label="含税单价" align="center" prop="taxRate" width="100"></el-table-column>
          <el-table-column label="含税总价" align="center" prop="taxInclusiveTotalPrice" width="100"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <a class="red" @click="form.materialDetails.splice(scope.$index, 1)"
                >删除</a
              >
            </template>
          </el-table-column>
        </WmsTable>
      </div>
    </div>
    <el-dialog
      :visible="modalObj.show"
      :title="modalObj.title"
      :width="modalObj.width"
      @close="modalObj.cancel"
    >
      <template v-if="modalObj.component === 'add-item'">
        <el-form
          ref="addForm"
          :model="addForm"
          :rules="addRules"
          label-width="78px"
          class="dialog-form-two"
        >
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="分类" prop="categoryId">
                <WmsMaterialType
                  v-model="addForm.categoryId"
                  @treeselect="wmsMaterialType"
                ></WmsMaterialType>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="型号" prop="modelId">
                <WmsMaterialModel
                  @elselect="elselect"
                  v-model="addForm.modelId"
                ></WmsMaterialModel>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="厚度" prop="thicknessName">
                <el-input
                  v-model="addForm.thicknessName"
                  placeholder="厚度"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="宽幅" prop="widthName">
                <el-input
                  v-model="addForm.widthName"
                  placeholder="宽幅"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="规格" prop="specificationName">
                <el-input
                  v-model="addForm.specificationName"
                  placeholder="规格"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="仓库" prop="warehouseId">
                <WmsWarehouseCascader
                  @wareHouseSelect="wareHouseSelect"
                  v-model="addForm.warehouseId"
                ></WmsWarehouseCascader>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="仓位" prop="warehousePositionId">
                <WmsArea
                  @areaSelect="areaSelect"
                  v-model="addForm.warehousePositionId"
                ></WmsArea>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="需求时间" prop="demandDate">
                <el-date-picker
                  v-model="addForm.demandDate"
                  type="date"
                  placeholder="选择日期"
                  disabled
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="预计到货" prop="expectedArrivalDate">
                <el-date-picker
                  v-model="addForm.expectedArrivalDate"
                  type="date"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="在途信息" prop="inTransitInformation">
                <el-input
                  v-model="addForm.inTransitInformation"
                  placeholder="在途信息"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="性质" prop="natureName">
                <el-input
                  v-model="addForm.natureName"
                  placeholder="性质"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-model="addForm.remarks"
                  placeholder="备注"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider></el-divider>

          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="件数" prop="pieceCount">
                <el-input
                  v-model="addForm.pieceCount"
                  placeholder="件数"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="件数单位" prop="pieceUnit">
                <el-select v-model="addForm.pieceUnit" placeholder="请选择">
                  <el-option
                    v-for="item in dict.type.wms_piece_unit"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  >
                    {{ item.label }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="数量" prop="quantity">
                <el-input
                  v-model="addForm.quantity"
                  placeholder="数量"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单位" prop="unitName">
                <el-select v-model="addForm.unitName" placeholder="请选择">
                  <el-option
                    v-for="item in dict.type.wms_piece_unit"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  >
                    {{ item.label }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="单价" prop="unitPrice">
                <el-input
                  v-model="addForm.unitPrice"
                  placeholder="单价"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="计价数量" prop="valuationQuantity">
                <el-input
                  v-model="addForm.valuationQuantity"
                  placeholder="计价数量"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="计价单位" prop="valuationUnit">
                <el-select v-model="addForm.valuationUnit" placeholder="请选择">
                  <el-option
                    v-for="item in dict.type.wms_piece_unit"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  >
                    {{ item.label }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="金额" prop="amount">
                <el-input
                  v-model="addForm.amount"
                  placeholder="金额"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="税率%" prop="taxRate">
                <el-input
                  v-model="addForm.taxRate"
                  placeholder="税率%"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="含税单价" prop="taxInclusivePrice">
                <el-input
                  v-model="addForm.taxInclusivePrice"
                  placeholder="含税单价"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="含税总价" prop="taxInclusiveTotalPrice">
                <el-input
                  v-model="addForm.taxInclusiveTotalPrice"
                  placeholder="含税总价"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <span slot="footer">
        <el-button v-if="modalObj.cancel" @click="modalObj.cancel"
          >取消</el-button
        >
        <el-button v-if="modalObj.ok" type="primary" @click="modalObj.ok"
          >确认</el-button
        >
      </span>
    </el-dialog>
    <BatchWarehouseDialog
      :visible.sync="batchDialogVisible"
      :form-data.sync="batchForm"
      @confirmed="onBatchDialogFinished"
    ></BatchWarehouseDialog>
  </div>
</template>

<script>
import {
  addOrUpdateWmsReceiptOrder,
  getWmsReceiptOrder,
} from "@/api/wms/receiptOrder";
import { randomId } from "@/utils/RandomUtils";
import BatchWarehouseDialog from "@/views/components/wms/BatchWarehouseDialog/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import { itemTypeTreeselect } from "@/api/wms/itemType";
export default {
  name: "WmsReceiptOrder",
  components: { BatchWarehouseDialog, Treeselect },
  dicts: [
    "wms_bill_type",
    "wms_payment_type",
    "wms_currency",
    "wms_piece_unit",
  ],
  data() {
    return {
      addForm: {},
      addRules: {
        modelId: [
          { required: true, message: "型号不能为空", trigger: "blur" },
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "blur" },
        ],
        natureName: [
          { required: true, message: "性质不能为空", trigger: "blur" },
        ],
      },
      ids: [],
      // 非多个禁用
      multiple: true,
      // 批量设置仓库/库区
      batchDialogVisible: false,
      batchForm: {
        place: [],
      },
      // 表单参数
      form: {
        materialDetails: [],
        payableAmount: 0.0,
        supplierId: null,
      },
      // 表单校验
      rules: {
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "blur" },
        ],
        userId: [
          { required: true, message: "经手人不能为空", trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "部门不能为空", trigger: "blur" },
        ],
      },
      modalObj: {
        show: false,
        title: "",
        width: "70%",
        component: null,
        model: {},
        ok: () => {},
        cancel: () => {},
      },
      hasSupplier: false,
    };
  },
  watch: {
    "form.supplierId": {
      immediate: true,
      handler(value) {
        if (value) {
          this.hasSupplier = true;
        } else {
          this.hasSupplier = false;
        }
      },
    },
  },
  created() {
    const { id } = this.$route.query;
    if (id) {
      this.loadDetail(id);
    } else {
      this.reset();
    }
  },
  methods: {
    // 仓库
    wareHouseSelect(e) {
      this.addForm.warehouseName = e.name;
    },
    // 仓位
    areaSelect(e) {
      console.log("e", e);
      this.addForm.warehousePositionName = e.name;
    },
    // 型号
    elselect(e) {
      this.addForm.modelName = e.name;
    },
    // 分类
    wmsMaterialType(e) {
      this.addForm.categoryName = e.name;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
    /** 批量设置仓库/库区 */
    onBatchSetInventory() {
      const { materialDetails } = this.form;
      if (!materialDetails || materialDetails.length === 0) {
        this.$modal.msgError("请先添加物料");
        return;
      }
      // 未选中
      if (!this.ids.length) {
        this.$modal.msgError("请先选择物料");
        return;
      }
      this.batchDialogVisible = true;
    },
    onBatchDialogFinished() {
      this.batchDialogVisible = false;
      const [warehouseId, areaId, rackId] = this.batchForm.place || [];
      this.form.materialDetails.forEach((it) => {
        // 仅更新已选中
        if (this.ids.includes(it.id)) {
          it.place = [warehouseId, areaId, rackId].filter(Boolean);
        }
      });
    },
    /** 统计入库单金额 */
    selectMoney() {
      let sum = 0;
      this.form.materialDetails.map((item) => {
        if (!isNaN(parseFloat(item.money))) {
          sum += item.money;
        }
        return item.money;
      });
      this.form.payableAmount = sum;
    },
    cancel() {
      this.$tab.closeOpenPage({ path: "/wms/receiptOrder" });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        // const materialDetails = this.form.materialDetails.map((it) => {
        //   if (it.place) {
        //     it.prod.warehouseId = it.place[0];
        //     it.prod.areaId = it.place[1];
        //     it.prod.rackId = it.place[2];
        //   } else {
        //     it.prod.warehouseId = null;
        //     it.prod.areaId = null;
        //     it.prod.rackId = null;
        //   }
        //   return {
        //     itemId: it.prod.id,
        //     rackId: it.prod.rackId,
        //     areaId: it.prod.areaId,
        //     money: it.money,
        //     warehouseId: it.prod.warehouseId,
        //     planQuantity: it.planQuantity,
        //     realQuantity: it.realQuantity,
        //     receiptOrderStatus: it.receiptOrderStatus,
        //     delFlag: 0,
        //   };
        // });
        // materialDetails
        const req = { ...this.form };
        console.log("req",req)
        // return
        addOrUpdateWmsReceiptOrder(req).then((response) => {
          this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
          this.cancel();
        });
      });
    },
    loadDetail(id) {
      getWmsReceiptOrder(id).then((response) => {
        const { materialDetails, items } = response;
        const map = {};
        (items || []).forEach((it) => {
          map[it.id] = it;
        });
        materialDetails && materialDetails.forEach((it) => (it.prod = map[it.itemId]));
        this.form = {
          ...response,
          materialDetails,
        };
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        receiptOrderNo: "R-" + randomId(),
        receiptOrderType: "1",
        supplierId: null,
        orderNo: null,
        receiptOrderStatus: 0,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        materialDetails: [],
      };
      this.resetForm("form");
    },
    //添加物料明细按钮
    confirmSelectItem() {
      this.$refs["addForm"].validate((valid) => {
        if(!valid){
          return
        }
        this.form.materialDetails.push(JSON.parse(JSON.stringify(this.addForm)));
        this.addForm = {};
        this.closeModal();
      });
    },
    closeModal() {
      this.modalObj.show = false;
    },
    showAddItem() {
      try {
        // this.$refs["item-select"].initmaterialDetailsList(this.form.materialDetails);
      } catch (err) {}
      const ok = () => this.confirmSelectItem();
      const cancel = () => this.closeModal();
      this.modalObj = {
        show: true,
        title: "添加物料",
        width: "70%",
        component: "add-item",
        model: {},
        ok,
        cancel,
      };
    },
  },
};
</script>
<style lang="stylus">
.el-date-editor.el-input, .el-date-editor.el-input__inner {
  width: 100%;
}

.receipt-order-edit-wrapper {
  .receipt-order-content {
    width: 95%;
    min-width: 900px;
    margin: 0 auto;
  }
}
</style>
